anti-forgery tokens implementation in asp.net web api

Bala Subrahmanya Gopal Jataprolu 0 Reputation points
2024-07-19T13:35:25.67+00:00

Can any one help me with anti-forgery tokens implementation in asp.net web api and AngularJS.

how do we maintain the forgery key in web api to validate the key for every request. Please provide the full example.

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,507 questions
{count} votes

2 answers

Sort by: Most helpful
  1. SurferOnWww 3,201 Reputation points
    2024-07-20T00:52:16+00:00

    There is no convenient way for the Web API to send the anti-forgery tokens to the client.

    Therefore, please consider using a token-based authentication and ssl as a countermeasure against CSRF attacks for the Web API.

    Typically, CSRF attacks are possible against web sites that use cookies for authentication, because browsers send all relevant cookies to the destination web site.

    Unlike ASP.NET Identity (cookie-based authentication), the browser will not automatically include the access token in subsequent requests. The application must do so explicitly. That's a good thing for the token-based authentication, because it limits CSRF vulnerabilities.

    0 comments No comments

  2. Bruce (SqlWork.com) 66,706 Reputation points
    2024-07-20T20:03:59.19+00:00

    Anti-forgery works by the site rendering a token in a form field and a token in a cookie. On postback the middleware compares the cookie value to the form value. The middleware only supports form postbacks. Typically a webapi uses json or xml, so the middleware can not get the postback value.

    to add support you add a route value or header that the angular api call sets. Then create your own middleware that compares the cookie to the value. If you want to update the token on each request, you custom middleware will need to update the cookie, and pass the new value in the response, maybe in a custom header.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.